<script setup>
import { useRoute, useRouter } from 'vue-router'
import { reactive, ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue';
const $route = useRoute();
const $router = useRouter()
import axios from "axios"
import { events } from '../../bus/bus';


//返回模块
const routerlink = () => {
    localStorage.setItem("roomName", undefined)
    $router.push({ name: "home" });
}

//因为mitt和fetch、axios好像有某些冲突，来不及了，重新获取一遍
//设备列表渲染模块
const deviceTotal = reactive([])
const deviceTotalTwice = reactive([])
const dataFormat = (res) => { //添加设备大类名称及大类下的小设备id、名称、大类名称、短地址
    if (deviceTotal.length == 0) {
        deviceTotal.push({ 'name': res[0].productName, 'equipment': [] })
    }
    for (let i = 0; i < res.length; i++) {
        for (let j = 0; j < deviceTotal.length; j++) {
            if (res[i].productName == deviceTotal[j].name) { break }
            else if (j == deviceTotal.length - 1) {
                deviceTotal.push({ 'name': res[i].productName, 'equipment': [] })
                break;
            }
        }
    }
    for (let i = 0; i < res.length; i++) {
        for (let j = 0; j < deviceTotal.length; j++) {
            if (res[i].productName == deviceTotal[j].name) {
                deviceTotal[j].equipment.push({ id: res[i].id ,deviceId: res[i].deviceId, deviceName: res[i].name, productName: res[i].productName, sadder: res[i].sadder })
            }
        }
    }
}

const twiceDataFormat = (respon) => {//添加小设备对应的房间
    for (let i = 0; i < deviceTotal.length; i++) {
        for (let j = 0; j < deviceTotal[i].equipment.length; j++) {
            deviceTotal[i].equipment[j].room = "未知房间"
        }
    }
    for (let i = 0; i < deviceTotal.length; i++) {
        for (let j = 0; j < deviceTotal[i].equipment.length; j++)
            for (let k = 0; k < respon.length; k++) {
                for (let z = 0; z < respon[k].deviceList.length; z++) {
                    if (respon[k].deviceList[z].deviceId == deviceTotal[i].equipment[j].deviceId) {
                        deviceTotal[i].equipment[j].room = respon[k].name;
                    }
                }
            }
    }
}

const thirdthDataFormat = (res) => {//添加小设备对应的属性
    for (let j = 0; j < deviceTotal.length; j++) {
        for (let k = 0; k < deviceTotal[j].equipment.length; k++) {
            if (res[deviceTotal[j].equipment[k].sadder] != undefined) {
                deviceTotal[j].equipment[k].brightness = res[deviceTotal[j].equipment[k].sadder].brightness
                deviceTotal[j].equipment[k].humidity = res[deviceTotal[j].equipment[k].sadder].humidity
                deviceTotal[j].equipment[k].left = res[deviceTotal[j].equipment[k].sadder].left
                deviceTotal[j].equipment[k].right = res[deviceTotal[j].equipment[k].sadder].right
                deviceTotal[j].equipment[k].temperature = res[deviceTotal[j].equipment[k].sadder].temperature
                deviceTotal[j].equipment[k].lockState = res[deviceTotal[j].equipment[k].sadder].lockState
            }
        }
    }
}

const forthDataFormat = () => {//格式小设备对应的属性
    for (let j = 0; j < deviceTotal.length; j++) {
        for (let k = 0; k < deviceTotal[j].equipment.length; k++) {
            if (deviceTotal[j].equipment[k].brightness != null) {
                for (let i = 0; i < deviceTotal[j].equipment[k].brightness.length; i += 2) {
                    switch (i) {
                        case 0:
                            deviceTotal[j].equipment[k].firstLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        case 2:
                            deviceTotal[j].equipment[k].secondLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        case 4:
                            deviceTotal[j].equipment[k].thirdLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        case 6:
                            deviceTotal[j].equipment[k].forthLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        default:
                            break;
                    }
                }
                if (deviceTotal[j].equipment[k].brightness == "00000000") {
                    deviceTotal[j].equipment[k].status = 0
                } else {
                    deviceTotal[j].equipment[k].status = 1
                }
            } else if ((deviceTotal[j].equipment[k].left != null) && (deviceTotal[j].equipment[k].right != null)) {
                if ((deviceTotal[j].equipment[k].left == 100) && (deviceTotal[j].equipment[k].right == 100)) {//反向判断，窗帘100反而是关上
                    deviceTotal[j].equipment[k].status = 0
                } else {
                    deviceTotal[j].equipment[k].status = 1
                }
            } else if (deviceTotal[j].equipment[k].productName == "网关") {
                deviceTotal[j].equipment[k].status = 1
            } else if (deviceTotal[j].equipment[k].lockState != null) {
                if (deviceTotal[j].equipment[k].lockState == "00") {
                    deviceTotal[j].equipment[k].status = 0
                } else {
                    deviceTotal[j].equipment[k].status = 1
                }
            }
        }
    }
}

const fifthFormatData = () => {
    for (let i = 0; i < deviceTotal.length; i++){
        for (let j = 0; j < deviceTotal[i].equipment.length; j++){
            deviceTotalTwice.push(deviceTotal[i].equipment[j])
        }
    }
    if (roomName.value == "") {
        for (let i = 0; i < deviceTotalTwice.length; i++) {
            deviceTotalTwice[i].choose = 0;
        }
    } else {
        for (let i = 0; i < deviceTotalTwice.length; i++) {
            if (deviceTotalTwice[i].room == roomName.value) {
                deviceTotalTwice[i].choose = 1;
            } else {
                deviceTotalTwice[i].choose = 0;
            }
        }
    }
}


//渲染设备列表模块
const cardRequest = axios.create({
    baseURL: 'api',
    timeout: 3000,
    withCredentials: true,
});
fetch("/api/getEndDeviceList ", {
    method: "GET",
})
    .then(res => res.json())
    .then(res => {
        dataFormat(res)
        cardRequest.post("/room", {
            type: "getRoomList"
        }).then((respon) => {
            allRoomIsp(respon.data.roomList)
            twiceDataFormat(respon.data.roomList)
            fetch("/api/getProperties ", {
                method: "GET",
            })
                .then(r => r.json())
                .then(r => {
                    thirdthDataFormat(r)
                    forthDataFormat()
                    fifthFormatData()
                    iconSet()
                    iconNow()
                })
        })
    })

const iconIs = (room,chooce) => {
    if (room == "未知房间") {
        return '\ue669'
    } else {
        return '\ue668'
    }
}

//上传新房间信息模块
const newRoomName = ref()
const allRoom = reactive([])
const allRoomIsp = (res) => {
    for (let i = 0; i < res.length; i++){
        allRoom.push(res[i].name)
    }
}
//跳转渲染模块
const roomName = ref("")
let temp = localStorage.getItem("roomName");
if (temp != "undefined") {
    temp = JSON.parse(localStorage.getItem("roomName"))
    newRoomName.value = temp
    roomName.value = temp;
}

const thorwError = ref(0)
const errorText = ref('')
const roomNameIsp = () => {//重名判断
    thorwError.value = 0
    if (newRoomName.value.length > 6) {
        thorwError.value = 1
        errorText.value = '房间名请小于六个字符，请重试'
        newRoomName.value = undefined
    }
    if (roomName.value == "") {
        for (let i = 0; i < allRoom.length; i++) {
            if (newRoomName.value == allRoom[i]) {
                thorwError.value = 1
                errorText.value = '房间重名请重试'
                newRoomName.value = undefined
            }
        }
    } else if(roomName.value != newRoomName.value){
        cardRequest.post("/room", {
            "type": "changeName",
            "name": String(roomName.value),
            "newName": String(newRoomName.value)
        })
    }
}
const addDevices = []
const addDeviceToRoom = (index) => {//设备选中
    if (deviceTotalTwice[index].room == "未知房间") {
        deviceTotalTwice[index].choose = !deviceTotalTwice[index].choose;
        if (!deviceTotalTwice[index].choose) {
            if (addDevices.indexOf(deviceTotalTwice[index].id)) {
                addDevices.splice(addDevices.indexOf(deviceTotalTwice[index].id), 1)
            }
        } else {
            if (addDevices.indexOf(deviceTotalTwice[index].id == -1)) {
                addDevices.push(deviceTotalTwice[index].id)
            }
        }
    }
}
const addNewRoom = () => {//添加
    if (newRoomName.value == undefined) {
        errorText.value = '房间名为空请重试'
        thorwError.value = 1
    }
    if (newRoomName.value && roomName.value == "") {
        cardRequest.post("/room", {
            "type": "addRoom",
            "name": String(newRoomName.value),
            "idList": addDevices
        })
        routerlink()
    } else if (roomName.value != "") {
        cardRequest.post("/room", {
            "type": "changeDevice",
            "name": String(newRoomName.value),
            "idList": addDevices
        })
        routerlink()
    }
}

const iconIsp = reactive([])
const iconSet = () => {
    for (let i = 0; i < deviceTotalTwice.length; i++){
        iconIsp.push('')
    }
}

const iconNow = () => {
    if (roomName.value == '') {
        for (let i = 0; i < deviceTotalTwice.length; i++) {
            if (deviceTotalTwice[i].room == "未知房间") {
                if (deviceTotalTwice[i].choose) {
                    iconIsp[i] = '\ue667'
                } else {
                    iconIsp[i] = '\ue669'
                }
            } else {
                iconIsp[i] = '\ue668'
            }
        }
    } else {
        for (let i = 0; i < deviceTotalTwice.length; i++) {
            if (deviceTotalTwice[i].room == "未知房间"|| deviceTotalTwice[i].room == roomName.value) {
                if (deviceTotalTwice[i].choose) {
                    iconIsp[i] = '\ue667'
                } else {
                    iconIsp[i] = '\ue669'
                }
            } else {
                iconIsp[i] = '\ue668'
            }
        }
    }
}
</script>

<template>
    <body class="w-[100vw] h-[100vh] relative select-none bg-[#fff2df] bg-cover bg-no-repeat bg-center flex justify-center items-center" style="background-image:url(../../background.png)">
        <div class="absolute left-0 top-0 text-[#ffbf40] mx-[1rem] my-[.5rem]" @click="routerlink()"><i class="iconfont">&#xe72e;</i></div>
        <div class="flex justify-center flex-col items-center w-5/6 h-[30rem] bg-gradient-to-r from-[#ffe259] to-[#ffa751] opacity-80 rounded-2xl">
            <name class="w-5/6 h-[2rem] mb-[1rem] flex flex-col items-center justify-center">
                <input @blur="roomNameIsp()" v-model="newRoomName" class="w-full h-full outline-none px-[.8rem] py-[1.2rem] rounded-xl" type="text" placeholder="请输入新房间名称">
                <error v-if="thorwError" class="text-[#ca0019] text-[.8rem] font-bold">{{'*' + errorText}}</error>
            </name>
            <devices class="w-5/6 h-[15rem] bg-white opacity-30 rounded-2xl overflow-auto">
                <device v-for="(item,index) in deviceTotalTwice" :key="index" class="flex items-center justify-center">
                    <div class="w-[96%] h-[3.5rem] bg-[#ffc773] rounded-2xl my-[.5rem] flex items-center">
                        <icon @click="addDeviceToRoom(index), iconNow()" class="w-1/4 flex justify-center items-center"><i class="iconfont">{{ iconIsp[index] }}</i></icon>
                        <div class="w-3/4 flex justify-around font-bold text-[1.1rem]">
                            <productname>{{ item.productName }}</productname>
                            <name>{{ item.deviceName }}</name>
                        </div>
                    </div>
                </device>
            </devices>
            <submit @click="addNewRoom()" class="w-5/6 h-[2.4rem] mt-[.6rem] opacity-60 bg-white rounded-xl flex items-center justify-center hover:opacity-40"> 
                <div class="text-[1.5rem] text-[#e29c45] font-bold">{{ roomName?"完成修改":"新建房间" }}</div>
            </submit>
        </div>
    </body>
</template>

<style scoped>
@font-face {
  font-family: 'iconfont';  /* Project id 4312277 */
  src: url('//at.alicdn.com/t/c/font_4312277_6b362zuo5el.woff2?t=1705412613518') format('woff2'),
       url('//at.alicdn.com/t/c/font_4312277_6b362zuo5el.woff?t=1705412613518') format('woff'),
       url('//at.alicdn.com/t/c/font_4312277_6b362zuo5el.ttf?t=1705412613518') format('truetype');
}
.iconfont{
    font-family:"iconfont" !important;
    font-size:32px;
    font-style:normal;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;
}
</style>